package m3;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.*;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

public class Consumer {
    public static void main(String[] args) throws Exception {
        //创建消费者对象
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer3");
        //设置name server
        consumer.setNamesrvAddr("192.168.64.141:9876");
        //设置从哪里订阅消息
        consumer.subscribe("Topic3", "*");
        //注册消息监听器[registerMessageListener]
        consumer.registerMessageListener(new MessageListenerConcurrently() {
   //Concurrently------------Orderly
            @Override //ConsumeOrderlyStatus+ConsumeOrderlyContext
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeOrderlyContext) {
                String t = Thread.currentThread().getName();
                for (MessageExt msg : list) {
                    System.out.println(t+" - "+ msg + " - " +new String(msg.getBody()));

                }
                if (Math.random()<0.5) {
                    System.out.println("消息处理完成");
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                } else {
                    System.out.println("消息处理失败, 要求服务器稍后重试发送消息");
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }

            }
        });
        //启动
        consumer.start();
    }
}
